﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Castle.Windsor;
using Castle.Windsor.Installer;
using MoleCart.Web.Ioc;
using System.IO;

namespace MoleCart.Web
{
	public class MvcApplication : System.Web.HttpApplication
	{
        private static IWindsorContainer container;

		public static void RegisterRoutes (RouteCollection routes)
		{
			routes.IgnoreRoute ("{resource}.axd/{*pathInfo}");
			//忽略favicon.ico
            routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });

			routes.MapRoute (
				"Default",
				"{controller}/{action}/{id}",
				new { controller = "Home", action = "Index", id = "" }
			);

		}

		public static void RegisterGlobalFilters (GlobalFilterCollection filters)
		{
			filters.Add (new HandleErrorAttribute ());
		}

		protected void Application_Start ()
		{
			AreaRegistration.RegisterAllAreas ();
			RegisterGlobalFilters (GlobalFilters.Filters);
			RegisterRoutes (RouteTable.Routes);
            InitializeWindsor();
		}

        protected void Application_End() {
            container.Dispose();
        }

        protected virtual void InitializeWindsor() {
            if (container == null) {
                // create a new Windsor Container
                
                string path = Path.Combine(Server.MapPath("Configuration"), "Windsor.config");
                container = ContainerBuilder.Build(path);

                // set the controller factory to the Windsor controller factory (in MVC Contrib)
                ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container));
            }
        }
	}
}
